#ifndef file_reader_h__
#define file_reader_h__

#include "common.h"
#include "request.h"
#include "boost/regex.hpp"

struct file_form
{
	static std::string form_data_boundary(const request& req)
	{
		auto content_type = req.get_header_value("Content-Type");
		auto nboundary = content_type.find("boundary=");
		if (std::string::npos == nboundary)
			return "";
		auto boundary = "--" + content_type.substr(nboundary + strlen("boundary="), std::string::npos);
		return std::move(boundary);
	}

	static bool parse_file_form(const std::string& boundary, std::string& body, std::string& fform)
	{
		auto end_boundary = boundary + "--\r\n";
		if (!body.compare(end_boundary))
			return false;

		auto field_begin = body.find(boundary);

		if (std::string::npos == field_begin)
			return false;

		body = body.substr(field_begin + boundary.length(), body.length() - field_begin - boundary.length());

		auto field_end = body.find(boundary);
		fform = body.substr(0, field_end);
		body = body.substr(field_end, std::string::npos);
		return true;
	}
};

class file_reader
{
public:
	bool parse_form_data(std::string body)
	{
		//file
		boost::regex file_name_rgx("filename=\"[a-zA-Z0-9\.-_]*\"");
		boost::smatch result;
		if (!boost::regex_search(body, result, file_name_rgx))
			return false;
		auto filename = result[0].str();
		_filename = filename.substr(strlen("filename=\""), filename.length() - strlen("filename=\"") - 1);
		boost::regex content_type_rgx("Content-Type: [a-zA-z\/-]*");
		if (!boost::regex_search(body, result, content_type_rgx))
			return false;
		auto content_type = result[0].str() + "\r\n\r\n";
		_content = body.substr(body.find(content_type) + content_type.length(), body.length() - body.find(content_type) - content_type.length() - strlen("\r\n"));
		_content.erase(std::remove(_content.begin(), _content.end(), '\r'), _content.end());
		return true;
	}

	void save(const char* dir)
	{
		auto full_path = dir + _filename;
		if (!boost::filesystem::is_directory(dir))
			boost::filesystem::create_directories(dir);
		if (boost::filesystem::exists(full_path))
		{
			LOGE("%s has been exist", _filename);
			return;
		}
		std::ofstream out(full_path);
		if (!out)
		{
			LOGE("create %s error", full_path);
			return;
		}
		out << _content;
		out.flush();
		out.close();
	}
private:
	std::string _filename;
	std::string _content;
};
#endif // file_reader_h__